package com.workstudy.wstudy.controller;

import java.util.List;
import java.util.stream.Collectors;

import com.workstudy.common.constant.UserConstants;
import com.workstudy.common.core.domain.entity.SysRole;
import com.workstudy.common.core.domain.entity.SysUser;
import com.workstudy.common.utils.ShiroUtils;
import com.workstudy.common.utils.StringUtils;
import com.workstudy.system.service.ISysPostService;
import com.workstudy.system.service.ISysRoleService;
import com.workstudy.system.service.ISysUserService;
import com.workstudy.wstudy.domain.WstStudent;
import com.workstudy.wstudy.service.IWstStudentService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.workstudy.common.annotation.Log;
import com.workstudy.common.enums.BusinessType;
import com.workstudy.wstudy.domain.WstTeacher;
import com.workstudy.wstudy.service.IWstTeacherService;
import com.workstudy.common.core.controller.BaseController;
import com.workstudy.common.core.domain.AjaxResult;
import com.workstudy.common.utils.poi.ExcelUtil;
import com.workstudy.common.core.page.TableDataInfo;

/**
 * 教师管理Controller
 * 
 * @author sun
 * @date 2021-04-04
 */
@Controller
@RequestMapping("/wstudy/teacher")
public class WstTeacherController extends BaseController
{
    private String prefix = "wstudy/teacher";

    @Autowired
    private IWstTeacherService wstTeacherService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysPostService postService;

    @RequiresPermissions("wstudy:teacher:view")
    @GetMapping()
    public String teacher()
    {
        return prefix + "/teacher";
    }

    /**
     * 查询教师管理列表
     */
    @RequiresPermissions("wstudy:teacher:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(WstTeacher wstTeacher)
    {
        startPage();
        List<WstTeacher> list = wstTeacherService.selectWstTeacherList(wstTeacher);
        return getDataTable(list);
    }

    /**
     * 导出教师管理列表
     */
    @RequiresPermissions("wstudy:teacher:export")
    @Log(title = "教师管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(WstTeacher wstTeacher)
    {
        List<WstTeacher> list = wstTeacherService.selectWstTeacherList(wstTeacher);
        ExcelUtil<WstTeacher> util = new ExcelUtil<WstTeacher>(WstTeacher.class);
        return util.exportExcel(list, "teacher");
    }

    /**
     * 新增教师管理
     */
    @GetMapping("/add")
    public String add(ModelMap mmap)
    {
        mmap.put("roles", roleService.selectRoleAll().stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        mmap.put("posts", postService.selectPostAll());
        return prefix + "/add";
    }

    /**
     * 新增保存教师管理
     */
    @RequiresPermissions("wstudy:teacher:add")
    @Log(title = "教师管理", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(WstTeacher wstTeacher)
    {
        SysUser user = wstTeacher;
        if (UserConstants.USER_NAME_NOT_UNIQUE.equals(userService.checkLoginNameUnique(user.getLoginName())))
        {
            return error("新增用户'" + user.getLoginName() + "'失败，登录账号已存在");
        }
        else if (StringUtils.isNotEmpty(user.getPhonenumber())
                && UserConstants.USER_PHONE_NOT_UNIQUE.equals(userService.checkPhoneUnique(user)))
        {
            return error("新增用户'" + user.getLoginName() + "'失败，手机号码已存在");
        }
        else if (StringUtils.isNotEmpty(user.getEmail())
                && UserConstants.USER_EMAIL_NOT_UNIQUE.equals(userService.checkEmailUnique(user)))
        {
            return error("新增用户'" + user.getLoginName() + "'失败，邮箱账号已存在");
        }
        return toAjax(wstTeacherService.insertWstTeacher(wstTeacher));
    }

    /**
     * 修改教师管理
     */
    @GetMapping("/edit/{teacherId}")
    public String edit(@PathVariable("teacherId") Long teacherId, ModelMap mmap)
    {
        Long userId = teacherId;
        List<SysRole> roles = roleService.selectRolesByUserId(userId);
        mmap.put("user", userService.selectUserById(userId));
        mmap.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        mmap.put("posts", postService.selectPostsByUserId(userId));
        WstTeacher wstTeacher = wstTeacherService.selectWstTeacherById(teacherId);
        mmap.put("wstTeacher", wstTeacher);
        return prefix + "/edit";
    }

    /**
     * 教师管理 详情
     */
    @GetMapping("/details/{teacherId}")
    public String details(@PathVariable("teacherId") Long teacherId, ModelMap mmap)
    {
        Long userId = teacherId;
        List<SysRole> roles = roleService.selectRolesByUserId(userId);
        mmap.put("user", userService.selectUserById(userId));
        mmap.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        mmap.put("posts", postService.selectPostsByUserId(userId));
        WstTeacher wstTeacher = wstTeacherService.selectWstTeacherById(teacherId);
        mmap.put("wstTeacher", wstTeacher);
        return prefix + "/details";
    }

    /**
     * 修改保存教师管理
     */
    @RequiresPermissions("wstudy:teacher:edit")
    @Log(title = "教师管理", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(WstTeacher wstTeacher)
    {
        SysUser user = wstTeacher;
        userService.checkUserAllowed(user);
        if (StringUtils.isNotEmpty(user.getPhonenumber())
                && UserConstants.USER_PHONE_NOT_UNIQUE.equals(userService.checkPhoneUnique(user)))
        {
            return error("修改用户'" + user.getLoginName() + "'失败，手机号码已存在");
        }
        else if (StringUtils.isNotEmpty(user.getEmail())
                && UserConstants.USER_EMAIL_NOT_UNIQUE.equals(userService.checkEmailUnique(user)))
        {
            return error("修改用户'" + user.getLoginName() + "'失败，邮箱账号已存在");
        }
        user.setUpdateBy(ShiroUtils.getLoginName());
        return toAjax(wstTeacherService.updateWstTeacher(wstTeacher));
    }

    /**
     * 删除教师管理
     */
    @RequiresPermissions("wstudy:teacher:remove")
    @Log(title = "教师管理", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(wstTeacherService.deleteWstTeacherByIds(ids));
    }
}
